package com.glowdayz.glowmee;

import java.io.File;
import java.io.IOException;

import kankan.wheel.widget.OnWheelChangedListener;
import kankan.wheel.widget.OnWheelScrollListener;
import kankan.wheel.widget.WheelView;
import kankan.wheel.widget.adapters.AbstractWheelTextAdapter;
import kankan.wheel.widget.adapters.ArrayWheelAdapter;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.PorterDuff;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.glowdayz.common.ActivityManager;
import com.glowdayz.common.CDialog;
import com.glowdayz.common.DateTime;
import com.glowdayz.common.HttpHandler;
import com.glowdayz.common.HttpHandler.FileInfo;
import com.glowdayz.common.ImageSelectHelperActivity;
import com.glowdayz.common.XmlParser;
import com.glowdayz.model.AddItem;
import com.glowdayz.model.CommonCodeCMD;
import com.mikhaellopez.circularimageview.CircularImageView;

public class JoinSecond extends ImageSelectHelperActivity implements OnClickListener, OnItemSelectedListener {
	
	private ActivityManager am = ActivityManager.getInstance();
	
	CircularImageView userImg = null;
	TextView nickName = null;
	Spinner gender = null, birthYear = null, skinType = null;
	Button locationBt = null;
	ImageView okBt = null;
	
	String[] birthYearArr = null, skinTypeArr = null, locationArr = null, location2Arr = null;
	String locationUrl = "", sido = "", gugun = "", addUrl = "";
	String genderText = "", birthYearText = "", skinTypeText = "", locationText = "";
	int paramIdx;
	
	private boolean scrolling = false;
	WheelView country = null, city = null;
	boolean isImage = false;

	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_join_second);
		
		am.addActivity(this);
		
		genderText = "";
		birthYearText = "";
		skinTypeText = "";
		locationText = "";
		
		ImageView backBt = (ImageView) findViewById(R.id.backBt);
		backBt.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
                        view.invalidate();
                        break;
                    }
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().clearColorFilter();
                        view.invalidate();
                        break;
                    }
                }
                return false;
            }
        });
		backBt.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		TextView textTitle = (TextView) findViewById(R.id.textTitle);
		textTitle.setText("추가정보입력");
		
		Intent fromIntent = getIntent();
		paramIdx = fromIntent.getIntExtra("PARAM_idx", 0);
		String paramNickName = fromIntent.getStringExtra("PARAM_nickName");
		
		userImg = (CircularImageView) findViewById(R.id.userImg);
		nickName = (TextView) findViewById(R.id.nickName);
		nickName.setText(paramNickName);
		
		String[] genderArr = {"성별", "남자" , "여자"};
		gender = (Spinner) findViewById(R.id.gender);
		gender.setPrompt("성별을 선택하세요.");
		gender.setOnItemSelectedListener(this);
		ArrayAdapter<String> gender_adapter = new ArrayAdapter<String>(JoinSecond.this, R.layout.spinner_item, genderArr);
		gender_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		gender.setAdapter(gender_adapter);
		
		birthYear = (Spinner) findViewById(R.id.birthYear);
		birthYear.setPrompt("출생년도를 선택하세요.");
		birthYear.setOnItemSelectedListener(this);
		
		skinType = (Spinner) findViewById(R.id.skinType);
		skinType.setPrompt("피부타입을 선택하세요.");
		skinType.setOnItemSelectedListener(this);
		
		okBt = (ImageView) findViewById(R.id.okBt);
		okBt.setEnabled(false);
		okBt.setImageAlpha(150);
		okBt.setOnClickListener(this);
		locationBt = (Button) findViewById(R.id.locationBt);
		locationBt.setOnClickListener(this);
		
		ImageSelectHelperActivity.file_name = DateTime.getInstance().getNowDateTimeString() + ".jpg";
		ImageSelectHelperActivity.isImage = false;
		
		findViewById(R.id.userImg).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                setImageSizeBoundary(400); // optional. default is 500.
                setCropOption(1, 1);  // optional. default is no crop.
                //setCustomButtons(btnGallery, btnCamera, btnCancel); // you can set these buttons.
                startSelectImage();
            }
        });
		
		(new BirthYearWorker()).execute();
		(new SkinTypeWorker()).execute();
		(new LocationWorker()).execute();
		
	}
	
	public class BirthYearWorker extends AsyncTask<Object, CommonCodeCMD, Object> {
		@Override
		protected void onPreExecute() {
			CDialog.showLoading(JoinSecond.this);
		}
		
		@Override
		protected Object doInBackground(Object... params) {
			Object result = null;
			
			// 접속할 주소 정의
			String url = getResources().getString(R.string.server_url) + "/glowmee/listCommonXml.do?parentId=출생년도&order=desc";
			
			// XML 파서 생성
			XmlPullParser parser = XmlParser.getInstance().getParser(url);
			
			// 통신 실패시 예외처리
			if (parser == null) {
				this.cancel(true);
				return null;
			}
			
			try {
				String tag = null;
				int type = parser.getEventType();

				/** 읽은 내용을 담기 위한 변수 */
				int idCommon = 0;
				int parentId = 0;
				String commonText = null;
				int sortKey = 0;
				int isDisplay = 0;
				String create_date = null;
				String modified_date = null;
				int count = 1;

				// 파싱 처리를 위한 반복 시작
				while (type != XmlPullParser.END_DOCUMENT) {
					// 읽은 태그의 이름
					tag = parser.getName();

					// 현재 읽고 있는 태그의 종류별로 분기
					switch (type) {
					case XmlPullParser.START_TAG:
						/** 원하는 종류의 시작태그를 만났을 때, 값을 추출 */
						if (tag.equals("totalArticleCount")) {
							parser.next();
							birthYearArr = new String[Integer.parseInt(parser.getText()) + 1];
							birthYearArr[0] = "출생년도";
						} else if (tag.equals("idCommon")) {
							parser.next();
							idCommon = Integer.parseInt(parser.getText());
						} else if (tag.equals("parentId")) {
							parser.next();
							parentId = Integer.parseInt(parser.getText());
						} else if (tag.equals("commonText")) {
							parser.next();
							commonText = parser.getText();
						} else if (tag.equals("sortKey")) {
							parser.next();
							sortKey = Integer.parseInt(parser.getText());
						} else if (tag.equals("isDisplay")) {
							parser.next();
							isDisplay = Integer.parseInt(parser.getText());
						} else if (tag.equals("create_date")) {
							parser.next();
							create_date = parser.getText();
						} else if (tag.equals("modified_date")) {
							parser.next();
							modified_date = parser.getText();
						}
						
						break;

					case XmlPullParser.END_TAG:
						if (tag.equals("item")) {
							CommonCodeCMD item = new CommonCodeCMD(idCommon, parentId, commonText, sortKey, isDisplay, create_date, modified_date);
							birthYearArr[count] = item.getCommonText();
							count++;
						}
						break;
					}

					// 다음 태그로 이동하고, 상태값을 변경
					type = parser.next();
				}

			} catch (XmlPullParserException e) {
				System.out.println("파서 생성 실패 >> " + e.toString());
			} catch (IOException e) {
				System.out.println("파서 읽기 실패 >> " + e.toString());
			}
			
			return result;
		}

		@Override
		protected void onProgressUpdate(CommonCodeCMD... param) {
		}

		@Override
		protected void onPostExecute(Object param) {
			ArrayAdapter<String> birthYear_adapter = new ArrayAdapter<String>(JoinSecond.this, R.layout.spinner_item, birthYearArr);
			birthYear_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			birthYear.setAdapter(birthYear_adapter);
			
			CDialog.hideLoading();
		}
		
		@Override
		protected void onCancelled() {
			CDialog.hideLoading();
			AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(JoinSecond.this, android.R.style.Theme_Holo_Light_Dialog));
			alert.setMessage("일시적인 통신에러입니다.");
			alert.setCancelable(false);
			alert.setPositiveButton("다시 시도", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					(new BirthYearWorker()).execute();
				}
			});
			alert.setNegativeButton("뒤로 가기", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			});
			alert.create();
			alert.show();
		}
	}
	
	public class SkinTypeWorker extends AsyncTask<Object, CommonCodeCMD, Object> {
		@Override
		protected void onPreExecute() {
			CDialog.showLoading(JoinSecond.this);
		}
		
		@Override
		protected Object doInBackground(Object... params) {
			Object result = null;
			
			// 접속할 주소 정의
			String url = getResources().getString(R.string.server_url) + "/glowmee/listCommonXml.do?parentId=피부";
			
			// XML 파서 생성
			XmlPullParser parser = XmlParser.getInstance().getParser(url);
			
			// 통신 실패시 예외처리
			if (parser == null) {
				this.cancel(true);
				return null;
			}
			
			try {
				String tag = null;
				int type = parser.getEventType();

				/** 읽은 내용을 담기 위한 변수 */
				int idCommon = 0;
				int parentId = 0;
				String commonText = null;
				int sortKey = 0;
				int isDisplay = 0;
				String create_date = null;
				String modified_date = null;
				int count = 1;

				// 파싱 처리를 위한 반복 시작
				while (type != XmlPullParser.END_DOCUMENT) {
					// 읽은 태그의 이름
					tag = parser.getName();

					// 현재 읽고 있는 태그의 종류별로 분기
					switch (type) {
					case XmlPullParser.START_TAG:
						/** 원하는 종류의 시작태그를 만났을 때, 값을 추출 */
						if (tag.equals("totalArticleCount")) {
							parser.next();
							skinTypeArr = new String[Integer.parseInt(parser.getText()) + 1];
							skinTypeArr[0] = "피부타입";
						} else if (tag.equals("idCommon")) {
							parser.next();
							idCommon = Integer.parseInt(parser.getText());
						} else if (tag.equals("parentId")) {
							parser.next();
							parentId = Integer.parseInt(parser.getText());
						} else if (tag.equals("commonText")) {
							parser.next();
							commonText = parser.getText();
						} else if (tag.equals("sortKey")) {
							parser.next();
							sortKey = Integer.parseInt(parser.getText());
						} else if (tag.equals("isDisplay")) {
							parser.next();
							isDisplay = Integer.parseInt(parser.getText());
						} else if (tag.equals("create_date")) {
							parser.next();
							create_date = parser.getText();
						} else if (tag.equals("modified_date")) {
							parser.next();
							modified_date = parser.getText();
						}
						
						break;

					case XmlPullParser.END_TAG:
						if (tag.equals("item")) {
							CommonCodeCMD item = new CommonCodeCMD(idCommon, parentId, commonText, sortKey, isDisplay, create_date, modified_date);
							skinTypeArr[count] = item.getCommonText();
							count++;
						}
						break;
					}

					// 다음 태그로 이동하고, 상태값을 변경
					type = parser.next();
				}

			} catch (XmlPullParserException e) {
				System.out.println("파서 생성 실패 >> " + e.toString());
			} catch (IOException e) {
				System.out.println("파서 읽기 실패 >> " + e.toString());
			}
			
			return result;
		}

		@Override
		protected void onProgressUpdate(CommonCodeCMD... param) {
		}

		@Override
		protected void onPostExecute(Object param) {
			ArrayAdapter<String> skinType_adapter = new ArrayAdapter<String>(JoinSecond.this, R.layout.spinner_item, skinTypeArr);
			skinType_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			skinType.setAdapter(skinType_adapter);
			
			CDialog.hideLoading();
		}
		
		@Override
		protected void onCancelled() {
			CDialog.hideLoading();
			AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(JoinSecond.this, android.R.style.Theme_Holo_Light_Dialog));
			alert.setMessage("일시적인 통신에러입니다.");
			alert.setCancelable(false);
			alert.setPositiveButton("다시 시도", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					(new SkinTypeWorker()).execute();
				}
			});
			alert.setNegativeButton("뒤로 가기", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			});
			alert.create();
			alert.show();
		}
	}
	
	public class LocationWorker extends AsyncTask<Object, CommonCodeCMD, Object> {
		@Override
		protected void onPreExecute() {
			CDialog.showLoading(JoinSecond.this);
		}
		
		@Override
		protected Object doInBackground(Object... params) {
			Object result = null;
			
			// 접속할 주소 정의
			String url = getResources().getString(R.string.server_url) + "/glowmee/listCommonXml.do?parentId=도시";
			
			// XML 파서 생성
			XmlPullParser parser = XmlParser.getInstance().getParser(url);
			
			// 통신 실패시 예외처리
			if (parser == null) {
				this.cancel(true);
				return null;
			}
			
			try {
				String tag = null;
				int type = parser.getEventType();

				/** 읽은 내용을 담기 위한 변수 */
				int idCommon = 0;
				int parentId = 0;
				String commonText = null;
				int sortKey = 0;
				int isDisplay = 0;
				String create_date = null;
				String modified_date = null;
				int count = 0;

				// 파싱 처리를 위한 반복 시작
				while (type != XmlPullParser.END_DOCUMENT) {
					// 읽은 태그의 이름
					tag = parser.getName();

					// 현재 읽고 있는 태그의 종류별로 분기
					switch (type) {
					case XmlPullParser.START_TAG:
						/** 원하는 종류의 시작태그를 만났을 때, 값을 추출 */
						if (tag.equals("totalArticleCount")) {
							parser.next();
							locationArr = new String[Integer.parseInt(parser.getText())];
							locationArr[0] = "거주지역";
						} else if (tag.equals("idCommon")) {
							parser.next();
							idCommon = Integer.parseInt(parser.getText());
						} else if (tag.equals("parentId")) {
							parser.next();
							parentId = Integer.parseInt(parser.getText());
						} else if (tag.equals("commonText")) {
							parser.next();
							commonText = parser.getText();
						} else if (tag.equals("sortKey")) {
							parser.next();
							sortKey = Integer.parseInt(parser.getText());
						} else if (tag.equals("isDisplay")) {
							parser.next();
							isDisplay = Integer.parseInt(parser.getText());
						} else if (tag.equals("create_date")) {
							parser.next();
							create_date = parser.getText();
						} else if (tag.equals("modified_date")) {
							parser.next();
							modified_date = parser.getText();
						}
						
						break;

					case XmlPullParser.END_TAG:
						if (tag.equals("item")) {
							CommonCodeCMD item = new CommonCodeCMD(idCommon, parentId, commonText, sortKey, isDisplay, create_date, modified_date);
							locationArr[count] = item.getCommonText();
							count++;
						}
						break;
					}

					// 다음 태그로 이동하고, 상태값을 변경
					type = parser.next();
				}

			} catch (XmlPullParserException e) {
				System.out.println("파서 생성 실패 >> " + e.toString());
			} catch (IOException e) {
				System.out.println("파서 읽기 실패 >> " + e.toString());
			}
			
			return result;
		}

		@Override
		protected void onProgressUpdate(CommonCodeCMD... param) {
		}

		@Override
		protected void onPostExecute(Object param) {
			CDialog.hideLoading();
		}
		
		@Override
		protected void onCancelled() {
			CDialog.hideLoading();
			AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(JoinSecond.this, android.R.style.Theme_Holo_Light_Dialog));
			alert.setMessage("일시적인 통신에러입니다.");
			alert.setCancelable(false);
			alert.setPositiveButton("다시 시도", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					(new LocationWorker()).execute();
				}
			});
			alert.setNegativeButton("뒤로 가기", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			});
			alert.create();
			alert.show();
		}
	}
	
	public class Location2Worker extends AsyncTask<Object, CommonCodeCMD, Object> {
		@Override
		protected void onPreExecute() {
		}
		
		@Override
		protected Object doInBackground(Object... params) {
			Object result = null;
			
			// XML 파서 생성
			XmlPullParser parser = XmlParser.getInstance().getParser(locationUrl);
			
			// 통신 실패시 예외처리
			if (parser == null) {
				this.cancel(true);
				return null;
			}
			
			try {
				String tag = null;
				int type = parser.getEventType();

				/** 읽은 내용을 담기 위한 변수 */
				int idCommon = 0;
				int parentId = 0;
				String commonText = null;
				int sortKey = 0;
				int isDisplay = 0;
				String create_date = null;
				String modified_date = null;
				int count = 0;

				// 파싱 처리를 위한 반복 시작
				while (type != XmlPullParser.END_DOCUMENT) {
					// 읽은 태그의 이름
					tag = parser.getName();

					// 현재 읽고 있는 태그의 종류별로 분기
					switch (type) {
					case XmlPullParser.START_TAG:
						/** 원하는 종류의 시작태그를 만났을 때, 값을 추출 */
						if (tag.equals("totalArticleCount")) {
							parser.next();
							location2Arr = new String[Integer.parseInt(parser.getText())];
						} else if (tag.equals("idCommon")) {
							parser.next();
							idCommon = Integer.parseInt(parser.getText());
						} else if (tag.equals("parentId")) {
							parser.next();
							parentId = Integer.parseInt(parser.getText());
						} else if (tag.equals("commonText")) {
							parser.next();
							commonText = parser.getText();
						} else if (tag.equals("sortKey")) {
							parser.next();
							sortKey = Integer.parseInt(parser.getText());
						} else if (tag.equals("isDisplay")) {
							parser.next();
							isDisplay = Integer.parseInt(parser.getText());
						} else if (tag.equals("create_date")) {
							parser.next();
							create_date = parser.getText();
						} else if (tag.equals("modified_date")) {
							parser.next();
							modified_date = parser.getText();
						}
						
						break;

					case XmlPullParser.END_TAG:
						if (tag.equals("item")) {
							CommonCodeCMD item = new CommonCodeCMD(idCommon, parentId, commonText, sortKey, isDisplay, create_date, modified_date);
							location2Arr[count] = item.getCommonText();
							count++;
						}
						break;
					}

					// 다음 태그로 이동하고, 상태값을 변경
					type = parser.next();
				}

			} catch (XmlPullParserException e) {
				System.out.println("파서 생성 실패 >> " + e.toString());
			} catch (IOException e) {
				System.out.println("파서 읽기 실패 >> " + e.toString());
			}
			
			return result;
		}

		@Override
		protected void onProgressUpdate(CommonCodeCMD... param) {
		}

		@Override
		protected void onPostExecute(Object param) {
			if (city != null && country != null) {
				updateCities(city, location2Arr, country.getCurrentItem());
			}
			gugun = location2Arr[0];
		}
		
		@Override
		protected void onCancelled() {
			AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(JoinSecond.this, android.R.style.Theme_Holo_Light_Dialog));
			alert.setMessage("일시적인 통신에러입니다.");
			alert.setCancelable(false);
			alert.setPositiveButton("다시 시도", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					(new Location2Worker()).execute();
				}
			});
			alert.setNegativeButton("뒤로 가기", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			});
			alert.create();
			alert.show();
		}
	}
	
	@SuppressLint("NewApi")
	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		switch(arg0.getId()) {
		case R.id.gender:
			if (arg2 == 0) {
				genderText = "";
			} else if (arg2 == 1) {
				genderText = "남자";
			} else if (arg2 == 2) {
				genderText = "여자";
			}
			
			if (!genderText.equals("") && !birthYearText.equals("") && !skinTypeText.equals("") && !locationText.equals("")) {
				okBt.setImageAlpha(255);
				okBt.setEnabled(true);
				okBt.setOnTouchListener(new OnTouchListener() {
		            @Override
		            public boolean onTouch(View v, MotionEvent event) {
		                switch (event.getAction()) {
		                    case MotionEvent.ACTION_DOWN: {
		                        ImageView view = (ImageView) v;
		                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
		                        view.invalidate();
		                        break;
		                    }
		                    case MotionEvent.ACTION_UP:
		                    case MotionEvent.ACTION_CANCEL: {
		                        ImageView view = (ImageView) v;
		                        view.getDrawable().clearColorFilter();
		                        view.invalidate();
		                        break;
		                    }
		                }
		                return false;
		            }
		        });
			} else {
				okBt.setImageAlpha(150);
				okBt.setEnabled(false);
			}
			
			break;
			
		case R.id.birthYear:
			if (arg2 == 0) {
				birthYearText = "";
			} else {
				birthYearText = birthYearArr[arg2].trim();
			}
			
			if (!genderText.equals("") && !birthYearText.equals("") && !skinTypeText.equals("") && !locationText.equals("")) {
				okBt.setImageAlpha(255);
				okBt.setEnabled(true);
				okBt.setOnTouchListener(new OnTouchListener() {
		            @Override
		            public boolean onTouch(View v, MotionEvent event) {
		                switch (event.getAction()) {
		                    case MotionEvent.ACTION_DOWN: {
		                        ImageView view = (ImageView) v;
		                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
		                        view.invalidate();
		                        break;
		                    }
		                    case MotionEvent.ACTION_UP:
		                    case MotionEvent.ACTION_CANCEL: {
		                        ImageView view = (ImageView) v;
		                        view.getDrawable().clearColorFilter();
		                        view.invalidate();
		                        break;
		                    }
		                }
		                return false;
		            }
		        });
			} else {
				okBt.setImageAlpha(150);
				okBt.setEnabled(false);
			}
			
			break;
			
		case R.id.skinType:
			if (arg2 == 0) {
				skinTypeText = "";
			} else {
				skinTypeText = skinTypeArr[arg2].trim();
			}
			
			if (!genderText.equals("") && !birthYearText.equals("") && !skinTypeText.equals("") && !locationText.equals("")) {
				okBt.setImageAlpha(255);
				okBt.setEnabled(true);
				okBt.setOnTouchListener(new OnTouchListener() {
		            @Override
		            public boolean onTouch(View v, MotionEvent event) {
		                switch (event.getAction()) {
		                    case MotionEvent.ACTION_DOWN: {
		                        ImageView view = (ImageView) v;
		                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
		                        view.invalidate();
		                        break;
		                    }
		                    case MotionEvent.ACTION_UP:
		                    case MotionEvent.ACTION_CANCEL: {
		                        ImageView view = (ImageView) v;
		                        view.getDrawable().clearColorFilter();
		                        view.invalidate();
		                        break;
		                    }
		                }
		                return false;
		            }
		        });
			} else {
				okBt.setImageAlpha(150);
				okBt.setEnabled(false);
			}
			
			break;
		}
	}
	
	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
	}

	@Override
	public void onClick(View v) {
		switch(v.getId()) {
		case R.id.okBt:
			
			if (genderText.equals("")) {
				Toast.makeText(this, "성별을 선택하세요.", Toast.LENGTH_SHORT).show();
				return;
			}
			
			if (birthYearText.equals("")) {
				Toast.makeText(this, "출생년도를 선택하세요.", Toast.LENGTH_SHORT).show();
				return;
			}
			
			if (skinTypeText.equals("")) {
				Toast.makeText(this, "피부타입을 선택하세요.", Toast.LENGTH_SHORT).show();
				return;
			}
			
			if (locationText.equals("")) {
				Toast.makeText(this, "거주지역을 선택하세요.", Toast.LENGTH_SHORT).show();
				return;
			}
			
			addUrl = getResources().getString(R.string.server_url) + "/glowmee/add2RegisterXml.do?";
			addUrl += "id=" + paramIdx + "&gender=" + genderText + "&birthYear=" + birthYearText + "&skinType=" + skinTypeText
					+ "&location=" + locationText;
			
			(new AddWorker()).execute();
			
			break;
		case R.id.locationBt:
			sido = "서울";
			gugun = "강남구";
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setCancelable(false);
			
			// 추가적인 레이아웃 XML을 로드함
			LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			final LinearLayout custom_view = (LinearLayout) inflater.inflate(R.layout.inc_location_dialog, null);
			
			country = (WheelView) custom_view.findViewById(R.id.country);
	        country.setVisibleItems(3);
	        country.setViewAdapter(new CountryAdapter(this));

	        city = (WheelView) custom_view.findViewById(R.id.city);
	        city.setVisibleItems(3);
	        
	        locationUrl = getResources().getString(R.string.server_url) +  "/glowmee/listCommonXml.do?sido=서울";
			(new Location2Worker()).execute();

	        country.addChangingListener(new OnWheelChangedListener() {
				@Override
				public void onChanged(WheelView wheel, int oldValue, int newValue) {
				    if (!scrolling) {
				        updateCities(city, location2Arr, newValue);
				    }
				}
			});
	        
	        country.addScrollingListener(new OnWheelScrollListener() {
	        	
	            @Override
				public void onScrollingStarted(WheelView wheel) {
	                scrolling = true;
	            }
	            @Override
				public void onScrollingFinished(WheelView wheel) {
	            	sido = locationArr[country.getCurrentItem()];
		        	locationUrl = getResources().getString(R.string.server_url) +  "/glowmee/listCommonXml.do?sido=" + locationArr[country.getCurrentItem()];
					(new Location2Worker()).execute();
	                scrolling = false;
	            }
	        });
	        
	        city.addScrollingListener(new OnWheelScrollListener() {
	        	
	            @Override
				public void onScrollingStarted(WheelView wheel) {
	                scrolling = true;
	            }
	            @Override
				public void onScrollingFinished(WheelView wheel) {
	            	gugun = location2Arr[city.getCurrentItem()];
	                scrolling = false;
	            }
	        });

	        country.setCurrentItem(0);
			
			// Dialog에 사용자 정의 레이아웃을 추가한다.
			builder.setView(custom_view);
			
			builder.setNegativeButton("취소", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
				}
			});
			
			builder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
				@SuppressLint("NewApi")
				@Override
				public void onClick(DialogInterface dialog, int which) {
					locationText = sido + " " + gugun;
					locationBt.setText(locationText);
					if (!genderText.equals("") && !birthYearText.equals("") && !skinTypeText.equals("") && !locationText.equals("")) {
						okBt.setImageAlpha(255);
						okBt.setEnabled(true);
						okBt.setOnTouchListener(new OnTouchListener() {
				            @Override
				            public boolean onTouch(View v, MotionEvent event) {
				                switch (event.getAction()) {
				                    case MotionEvent.ACTION_DOWN: {
				                        ImageView view = (ImageView) v;
				                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
				                        view.invalidate();
				                        break;
				                    }
				                    case MotionEvent.ACTION_UP:
				                    case MotionEvent.ACTION_CANCEL: {
				                        ImageView view = (ImageView) v;
				                        view.getDrawable().clearColorFilter();
				                        view.invalidate();
				                        break;
				                    }
				                }
				                return false;
				            }
				        });
					} else {
						okBt.setImageAlpha(150);
						okBt.setEnabled(false);
					}
				}
			});
			
			builder.create();
			builder.show();
			break;
		}
	}
	
	public class AddWorker extends AsyncTask<Object, AddItem, Object> {
		@Override
		protected void onPreExecute() {
			CDialog.showLoading(JoinSecond.this);
		}

		@Override
		protected Object doInBackground(Object... params) {
			Object result = null;
			
			File file = getSelectedImageFile();
			
			FileInfo fileInfo = HttpHandler.getInstance().createFile("file", file.getAbsolutePath());
			
			// XML 파서 생성
			XmlPullParser parser = null;
			
			if (ImageSelectHelperActivity.isImage == true) {
				parser = XmlParser.getInstance().getParserSingle(addUrl, fileInfo);
			} else {
				parser = XmlParser.getInstance().getParserSingle(addUrl, null);
			}
			
			// 통신 실패시 예외처리
			if (parser == null) {
				this.cancel(true);
				return null;
			}
			
			try {
				String tag = null;
				int type = parser.getEventType();
				
				/** 읽은 내용을 담기 위한 변수 */
				String rt = null;
				String rtmsg = null;
				int seq = 0;
				// 파싱 처리를 위한 반복 시작
				while (type != XmlPullParser.END_DOCUMENT) {
					// 읽은 태그의 이름
					tag = parser.getName();

					// 현재 읽고 있는 태그의 종류별로 분기
					switch (type) {
					case XmlPullParser.START_TAG:
						/** 원하는 종류의 시작태그를 만났을 때, 값을 추출 */
						if (tag.equals("rt")) {
							parser.next();
							rt = parser.getText();
						} else if (tag.equals("rtmsg")) {
							parser.next();
							rtmsg = parser.getText();
						} else if (tag.equals("seq")) {
							parser.next();
							seq = Integer.parseInt(parser.getText().trim());
						}
						
						break;

					case XmlPullParser.END_TAG:
						
						if (tag.equals("JSPglowmee")) {
							AddItem item = new AddItem(rt, rtmsg, seq);
							publishProgress(item);
						}
						break;
					}

					// 다음 태그로 이동하고, 상태값을 변경
					type = parser.next();
				}

			} catch (XmlPullParserException e) {
				System.out.println("파서 생성 실패 >> " + e.toString());
			} catch (IOException e) {
				System.out.println("파서 읽기 실패 >> " + e.toString());
			}
			
			return result;
		}

		@Override
		protected void onProgressUpdate(AddItem... param) {
			
			if (param[0].getRt().equals("SUCCESS")) {
				Intent intent = new Intent(JoinSecond.this, Index.class);
				finish();
				startActivity(intent);
			} else {
				AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(JoinSecond.this, android.R.style.Theme_Holo_Light_Dialog));
				alert.setTitle("실패");
				alert.setMessage(param[0].getRtmsg());
				alert.setCancelable(false);
				alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				});
				alert.create();
				alert.show();
			}
			
		}

		@Override
		protected void onPostExecute(Object param) {
			CDialog.hideLoading();
		}

		@Override
		protected void onCancelled() {
			CDialog.hideLoading();
			AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(JoinSecond.this, android.R.style.Theme_Holo_Light_Dialog));
			alert.setMessage("일시적인 통신에러입니다.");
			alert.setCancelable(false);
			alert.setPositiveButton("다시 시도", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					(new AddWorker()).execute();
				}
			});
			alert.setNegativeButton("뒤로 가기", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			});
			alert.create();
			alert.show();
		}
	}
	
	@Override
	public Bitmap fastblur(Bitmap sentBitmap, int radius) {

        // Stack Blur v1.0 from
        // http://www.quasimondo.com/StackBlurForCanvas/StackBlurDemo.html
        //
        // Java Author: Mario Klingemann <mario at quasimondo.com>
        // http://incubator.quasimondo.com
        // created Feburary 29, 2004
        // Android port : Yahel Bouaziz <yahel at kayenko.com>
        // http://www.kayenko.com
        // ported april 5th, 2012

        // This is a compromise between Gaussian Blur and Box blur
        // It creates much better looking blurs than Box Blur, but is
        // 7x faster than my Gaussian Blur implementation.
        //
        // I called it Stack Blur because this describes best how this
        // filter works internally: it creates a kind of moving stack
        // of colors whilst scanning through the image. Thereby it
        // just has to add one new block of color to the right side
        // of the stack and remove the leftmost color. The remaining
        // colors on the topmost layer of the stack are either added on
        // or reduced by one, depending on if they are on the right or
        // on the left side of the stack.
        //
        // If you are using this algorithm in your code please add
        // the following line:
        //
        // Stack Blur Algorithm by Mario Klingemann <mario@quasimondo.com>

        Bitmap bitmap = sentBitmap.copy(sentBitmap.getConfig(), true);

        if (radius < 1) {
            return (null);
        }

        int w = bitmap.getWidth();
        int h = bitmap.getHeight();

        int[] pix = new int[w * h];
        bitmap.getPixels(pix, 0, w, 0, 0, w, h);

        int wm = w - 1;
        int hm = h - 1;
        int wh = w * h;
        int div = radius + radius + 1;

        int r[] = new int[wh];
        int g[] = new int[wh];
        int b[] = new int[wh];
        int rsum, gsum, bsum, x, y, i, p, yp, yi, yw;
        int vmin[] = new int[Math.max(w, h)];

        int divsum = (div + 1) >> 1;
        divsum *= divsum;
        int dv[] = new int[256 * divsum];
        for (i = 0; i < 256 * divsum; i++) {
            dv[i] = (i / divsum);
        }

        yw = yi = 0;

        int[][] stack = new int[div][3];
        int stackpointer;
        int stackstart;
        int[] sir;
        int rbs;
        int r1 = radius + 1;
        int routsum, goutsum, boutsum;
        int rinsum, ginsum, binsum;

        for (y = 0; y < h; y++) {
            rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
            for (i = -radius; i <= radius; i++) {
                p = pix[yi + Math.min(wm, Math.max(i, 0))];
                sir = stack[i + radius];
                sir[0] = (p & 0xff0000) >> 16;
                sir[1] = (p & 0x00ff00) >> 8;
                sir[2] = (p & 0x0000ff);
                rbs = r1 - Math.abs(i);
                rsum += sir[0] * rbs;
                gsum += sir[1] * rbs;
                bsum += sir[2] * rbs;
                if (i > 0) {
                    rinsum += sir[0];
                    ginsum += sir[1];
                    binsum += sir[2];
                } else {
                    routsum += sir[0];
                    goutsum += sir[1];
                    boutsum += sir[2];
                }
            }
            stackpointer = radius;

            for (x = 0; x < w; x++) {

                r[yi] = dv[rsum];
                g[yi] = dv[gsum];
                b[yi] = dv[bsum];

                rsum -= routsum;
                gsum -= goutsum;
                bsum -= boutsum;

                stackstart = stackpointer - radius + div;
                sir = stack[stackstart % div];

                routsum -= sir[0];
                goutsum -= sir[1];
                boutsum -= sir[2];

                if (y == 0) {
                    vmin[x] = Math.min(x + radius + 1, wm);
                }
                p = pix[yw + vmin[x]];

                sir[0] = (p & 0xff0000) >> 16;
                sir[1] = (p & 0x00ff00) >> 8;
                sir[2] = (p & 0x0000ff);

                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];

                rsum += rinsum;
                gsum += ginsum;
                bsum += binsum;

                stackpointer = (stackpointer + 1) % div;
                sir = stack[(stackpointer) % div];

                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];

                rinsum -= sir[0];
                ginsum -= sir[1];
                binsum -= sir[2];

                yi++;
            }
            yw += w;
        }
        for (x = 0; x < w; x++) {
            rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
            yp = -radius * w;
            for (i = -radius; i <= radius; i++) {
                yi = Math.max(0, yp) + x;

                sir = stack[i + radius];

                sir[0] = r[yi];
                sir[1] = g[yi];
                sir[2] = b[yi];

                rbs = r1 - Math.abs(i);

                rsum += r[yi] * rbs;
                gsum += g[yi] * rbs;
                bsum += b[yi] * rbs;

                if (i > 0) {
                    rinsum += sir[0];
                    ginsum += sir[1];
                    binsum += sir[2];
                } else {
                    routsum += sir[0];
                    goutsum += sir[1];
                    boutsum += sir[2];
                }

                if (i < hm) {
                    yp += w;
                }
            }
            yi = x;
            stackpointer = radius;
            for (y = 0; y < h; y++) {
                // Preserve alpha channel: ( 0xff000000 & pix[yi] )
                pix[yi] = ( 0xff000000 & pix[yi] ) | ( dv[rsum] << 16 ) | ( dv[gsum] << 8 ) | dv[bsum];

                rsum -= routsum;
                gsum -= goutsum;
                bsum -= boutsum;

                stackstart = stackpointer - radius + div;
                sir = stack[stackstart % div];

                routsum -= sir[0];
                goutsum -= sir[1];
                boutsum -= sir[2];

                if (x == 0) {
                    vmin[y] = Math.min(y + r1, hm) * w;
                }
                p = x + vmin[y];

                sir[0] = r[p];
                sir[1] = g[p];
                sir[2] = b[p];

                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];

                rsum += rinsum;
                gsum += ginsum;
                bsum += binsum;

                stackpointer = (stackpointer + 1) % div;
                sir = stack[stackpointer];

                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];

                rinsum -= sir[0];
                ginsum -= sir[1];
                binsum -= sir[2];

                yi += w;
            }
        }
        bitmap.setPixels(pix, 0, w, 0, 0, w, h);

        return (bitmap);
	}
	
	/**
     * Updates the city wheel
     */
    private void updateCities(WheelView city, String[] cities, int index) {
        ArrayWheelAdapter<String> adapter = new ArrayWheelAdapter<String>(this, cities);
        adapter.setTextSize(20);
        city.setViewAdapter(adapter);
        city.setCurrentItem(0);
    }
    
    /**
     * Adapter for countries
     */
    private class CountryAdapter extends AbstractWheelTextAdapter {
        // Countries names
        //private String countries[] = new String[] {"USA", "Canada", "Ukraine", "France"};
        
        /**
         * Constructor
         */
        protected CountryAdapter(Context context) {
            super(context, R.layout.country_layout, NO_RESOURCE);
            setItemTextResource(R.id.country_name);
        }
        
        @Override
        public int getItemsCount() {
            return locationArr.length;
        }
        
        @Override
        protected CharSequence getItemText(int index) {
            return locationArr[index];
        }
    }
    
    @Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
	}
    
    @Override
	protected void onDestroy() {
		super.onDestroy();
		am.removeActivity(this);
	}

}
